package com.album.web.controller;

import com.album.common.cbb.RestResult;
import com.album.web.anno.MyLog;
import com.album.web.domain.AlbumBean;
import com.album.web.domain.FileBean;
import com.album.web.domain.UserBean;
import com.album.web.service.UserService;
import com.album.web.util.Result;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private UserService userService;

    @RequestMapping("/save")
    public String save(@RequestParam Map map) {
        final Object describle = map.get("describle");
        final Object title = map.get("title");
        final Object detail = map.get("detail");
        final Object img = map.get("img");
        UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
        jdbcTemplate.update("insert into news(describle,title,detail,img,createtime,username) values(?,?,?,?,?,?)", describle, title, detail, img, new Date().toLocaleString(), sessionUserBean.getUsername());
        return "ok";
    }


    @RequestMapping("/list")
    public Object saveNews(@RequestParam Map map) {
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from news order by id desc ");
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("primarySum", jdbcTemplate.queryForList("select sum(CASE tp.newsid WHEN ? THEN 1 ELSE 0 END) as 'primarySum' from news n left join t_primary tp on n.id = tp.newsid WHERE n.id = ?", list.get(i).get("id"), list.get(i).get("id")).get(0).get("primarySum"));
            list.get(i).put("commentSum", jdbcTemplate.queryForList("select sum(CASE c.newsid WHEN ? THEN 1 ELSE 0 END) as 'commentSum' from news n left join comment c on c.newsid = n.id WHERE n.id = ?", list.get(i).get("id"), list.get(i).get("id")).get(0).get("commentSum"));
        }
        return list;
    }

    @RequestMapping("/listByUserName")
    public Object listByUserName(@RequestParam Map map) {
        UserBean userBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from news where username = ? order by id desc ", userBean.getUsername());
        for (int i = 0; i < list.size(); i++) {
            list.get(i).put("primarySum", jdbcTemplate.queryForList("select sum(CASE tp.newsid WHEN ? THEN 1 ELSE 0 END) as 'primarySum' from news n left join t_primary tp on n.id = tp.newsid WHERE n.id = ?", list.get(i).get("id"), list.get(i).get("id")).get(0).get("primarySum"));
            list.get(i).put("commentSum", jdbcTemplate.queryForList("select sum(CASE c.newsid WHEN ? THEN 1 ELSE 0 END) as 'commentSum' from news n left join comment c on c.newsid = n.id WHERE n.id = ?", list.get(i).get("id"), list.get(i).get("id")).get(0).get("commentSum"));
        }
        return list;
    }


    @RequestMapping("/pinglun")
    public Object pinglun(@RequestParam Map map) {
        try {
            final Object content = map.get("content");
            final Object newsid = map.get("newsid");
            final Object parentId = map.get("parentId");
            UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
            jdbcTemplate.update("insert into comment(content,newsid,username,createtime) values(?,?,?,?)", content, newsid, sessionUserBean.getUsername(), new Date().toLocaleString());
            return "ok";
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    @RequestMapping("/reply")
    public Object reply(@RequestParam Map map) {
        try {
            final Object content = map.get("content");
            final Object parentId = map.get("parentId");
            UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
            jdbcTemplate.update("insert into comment(content,username,createtime,parentId) values(?,?,?,?)", content, sessionUserBean.getUsername(), new Date().toLocaleString(),parentId);
            return "ok";
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    @RequestMapping("/dianzan")
    public Object dianzan(@RequestParam Map map) {
        try {
            final Object newsid = map.get("newsid");
            UserBean sessionUserBean = (UserBean) SecurityUtils.getSubject().getPrincipal();
            jdbcTemplate.update("insert into t_primary(newsid,username) values(?,?)", newsid, sessionUserBean.getUsername());
            return "ok";
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return "fail";
    }

    @RequestMapping("/detail")
    public Object detail(@RequestParam Integer id) {
        final List<Map<String, Object>> mapList = jdbcTemplate.queryForList("SELECT *,\n" +
                "(select count(*)  from t_primary WHERE newsid=?) totalPrimary,\n" +
                "(select count(*)  from `comment` WHERE newsid=?) totalComment\n" +
                "from news where id=?", id, id, id);
        final List<Map<String, Object>> mapList1 = jdbcTemplate.queryForList("SELECT * from `comment` where newsid=?", id);
        Map map = new HashMap(20);
        map.put("detail", mapList.get(0));
        map.put("comment", mapList1);
        return map;
    }

    @RequestMapping("/detail2")
    public Object detail2(@RequestParam Integer id) {
        final List<Map<String, Object>> mapList = jdbcTemplate.queryForList("SELECT *,\n" +
                "(select count(*)  from t_primary WHERE newsid=?) totalPrimary,\n" +
                "(select count(*)  from `comment` WHERE newsid=?) totalComment\n" +
                "from news where id=?", id, id, id);
        final List<Map<String, Object>> mapList1 = jdbcTemplate.queryForList("SELECT * from `comment` where newsid=?", id);
        List<Map<String, Object>> list=new ArrayList<>();
        for (int i = 0; i < mapList1.size(); i++) {
            list = jdbcTemplate.queryForList("select * from `comment` where parentId = ? order by STR_TO_DATE(createtime, '%Y-%m-%d') DESC; ", (int)mapList1.get(i).get("id"));
            mapList1.get(i).put("childList",list);
        }

        Map map = new HashMap(20);
        map.put("detail", mapList.get(0));
        map.put("comment", mapList1);
        return map;
    }


    @ResponseBody
    @RequestMapping(value = "deleteNew/{id}")
    public Result deleteNewById(@PathVariable("id") String id) {
        jdbcTemplate.update("delete from news where id = ?", id);
        return new Result("删除成功");
    }

    @ResponseBody
    @RequestMapping(value = "deleteComment/{id}")
    public Result deleteCommentById(@PathVariable("id") String id) {
        jdbcTemplate.update("delete from comment where id = ?", id);
        return new Result("删除成功");
    }

}

